package com.ustc.hewei.nettyrpc2_0.netty.server.handler;

import com.ustc.hewei.nettyrpc2_0.common.enumeration.RpcError;
import com.ustc.hewei.nettyrpc2_0.common.exception.RpcException;
import com.ustc.hewei.nettyrpc2_0.common.warp.RpcRequest;
import com.ustc.hewei.nettyrpc2_0.zookeeper.register.ServiceRegister;
import lombok.extern.slf4j.Slf4j;

/**
 * @author hewei
 * @version 1.0
 * @description: 服务端处理请求，反射调用
 * @date 2022/9/13 21:01
 */

@Slf4j
public class RequestHandler {
    private final ServiceRegister serviceRegister;

    public RequestHandler(ServiceRegister serviceRegister) {
        this.serviceRegister = serviceRegister;
    }

    public Object handler(RpcRequest request) throws Exception {
        String serviceName = request.getInterfaceName();
        Object object = serviceRegister.getServiceObject(serviceName);
        if (object == null) {
            log.error("找不到接口 {} 的实现类", serviceName);
            throw new RpcException(RpcError.UNFOUNDED_INTERFACE_IMPLEMENT, String.format("接口名为 {%S}", serviceName));
        }
        String method = request.getMethodName();
        Class<?>[] paramsType = request.getParamTypes();
        Object[] params = request.getParameters();
        return object.getClass().getMethod(method, paramsType).invoke(object, params);
    }
}